import 'package:date_format/date_format.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:dio/dio.dart' as Dio;
import 'package:zootix/models/zt_im_conversation.model.dart';
import 'package:zootix/store/zt_im_chat.store.dart';

class ZtConversationController extends GetxController {
  RefreshController refreshController = RefreshController(initialRefresh: true);
  int page = 1;
  int limit = 15;
  int total = 0;
  RxBool isZtImStoreInit = RxBool(false);
  @override
  onReady() {
    super.onReady();
  }

  Future<List<ZtImConversationModel>> getData({bool isRefresh = false}) async {
    int time = DateTime.now().millisecondsSinceEpoch;
    if (isRefresh == true) {
      page = 1;
    } else {
      page++;
      time = ZtImChartStore.to.conversationList.last.operationTime!;
    }
    List<ZtImConversationModel> newListData =
        await ZtImChartStore.to.getConversations(limit: limit, time: time);
    if (newListData.isEmpty) {
      ZtImChartStore.to.conversationList.refresh();
    }
    isRefresh == true
        ? ZtImChartStore.to.conversationList.assignAll(newListData)
        : ZtImChartStore.to.conversationList.addAll(newListData);
    return newListData;
  }

  Future<void> onRefresh() async {
    if (Get.isRegistered<ZtImChartStore>()) {
      await getData(isRefresh: true).then((_) {
        refreshController.refreshCompleted(resetFooterState: true);
      }).catchError((_) {
        refreshController.refreshFailed();
      });
    }
  }

  Future<void> onLoading() async {
    await getData().then((_) {
      if (_.isEmpty) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }).catchError((_) {
      refreshController.loadFailed();
    });
  }

  String formatConverstaionDate(int sentTime) {
    DateTime sentDateTime = DateTime.fromMillisecondsSinceEpoch(sentTime);
    String sentDate = formatDate(sentDateTime, ['yyyy', '-', 'mm', '-', 'dd']);
    String today = formatDate(DateTime.now(), ['yyyy', '-', 'mm', '-', 'dd']);
    if (today == sentDate) {
      return formatDate(sentDateTime, ['HH', ':', 'nn']);
    }

    if (sentDateTime.year == DateTime.now().year) {
      return formatDate(sentDateTime, ['mm', '-', 'dd', ' ', 'hh', ':', 'nn']);
    } else {
      return formatDate(
          sentDateTime, ['yyyy', '-', 'mm', '-', 'dd', ' ', 'hh', ':', 'nn']);
    }
  }
}
